package api

import (
	"github.com/gin-gonic/gin"

	"pool/pool_backend/config"
	"pool/pool_backend/internal/api/handlers"
	"pool/pool_backend/internal/api/middleware"
	"pool/pool_backend/internal/service"
)

// Router API路由
type Router struct {
	engine      *gin.Engine
	userHandler *handlers.UserHandler
	claimHandler *handlers.ClaimHandler
}

// NewRouter 创建API路由
func NewRouter(
	cfg *config.ServerConfig,
	userService service.UserService,
	claimService service.ClaimService,
) *Router {
	// 设置运行模式
	gin.SetMode(cfg.Mode)

	// 创建gin引擎
	engine := gin.New()

	// 添加中间件
	engine.Use(middleware.LoggerMiddleware())
	engine.Use(gin.Recovery())
	engine.Use(middleware.CORSMiddleware())

	// 创建处理器
	userHandler := handlers.NewUserHandler(userService)
	claimHandler := handlers.NewClaimHandler(claimService)

	return &Router{
		engine:      engine,
		userHandler: userHandler,
		claimHandler: claimHandler,
	}
}

// Init 初始化路由
func (r *Router) Init() {
	// 健康检查
	r.engine.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status": "ok",
		})
	})

	// API路由组
	api := r.engine.Group("/v1")
	{
		// 用户相关路由
		user := api.Group("/user")
		{
			// 需要认证的路由
			authUser := user.Group("")
			// 暂时不使用JWT验证，后续再添加
			{
				// 绑定邀请人
				authUser.POST("/:address/bind", r.userHandler.BindInviter)
			}

			// 不需要认证的路由
			// 获取用户信息
			user.GET("/:address/info/", r.userHandler.GetUserInfo)
			// 获取用户下级
			user.POST("/:address/sub", r.userHandler.GetSubUsers)
			// 获取统计数据
			user.GET("/:address/data", r.userHandler.GetData)
		}

		// Claim相关路由
		claim := api.Group("")
		{
			// 获取Claim记录
			claim.POST("/reclaim/:address", r.claimHandler.GetClaimRecords)
			// 记录Check-In
			claim.POST("/checkin/:address", r.claimHandler.RecordCheckIn)
			// 领取用户的层级奖励
			claim.POST("/claim/:address",r.claimHandler.Claim)
		}
	}
}

// Run 运行服务器
func (r *Router) Run(port string) error {
	return r.engine.Run(port)
} 